package com.uit3j.cloud.search.listener;

import com.uit3j.cloud.api.product.bo.EsHotSearchBO;
import com.uit3j.cloud.api.product.feign.HotSearchFeignClient;
import com.uit3j.cloud.api.vo.search.HotSearchVO;
import com.uit3j.cloud.common.exception.Uit3jcloudException;
import com.uit3j.cloud.common.response.ServerResponseEntity;
import com.uit3j.cloud.common.rocketmq.config.RocketMqConstant;
import com.uit3j.cloud.common.util.Json;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.xcontent.XContentType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 热搜的监听
 * @author tan
 * @date 2024/07/10
 */
@Component
@RocketMQMessageListener(topic = RocketMqConstant.HOT_SEARCH_SAVE,consumerGroup = RocketMqConstant.HOT_SEARCH_SAVE)
public class HotSearchSaveConsumer implements RocketMQListener<HotSearchVO> {

    private static final Logger log = LoggerFactory.getLogger(HotSearchSaveConsumer.class);

    @Autowired
    private HotSearchFeignClient hotSearchFeignClient;

    @Autowired
    private RestHighLevelClient restHighLevelClient;


    /**
     * 插入热搜时，此时插入es
     */
    @Override
    public void onMessage(HotSearchVO sendHotSearch) {
        Long hotSearchId = sendHotSearch.getHotSearchId();
        ServerResponseEntity<EsHotSearchBO> esHotSearchResponse = hotSearchFeignClient.loadEsHotSearchBO(hotSearchId);
        IndexRequest request = new IndexRequest("hot_search");
        request.id(String.valueOf(hotSearchId));
        request.source(Json.toJsonString(esHotSearchResponse.getData()), XContentType.JSON);
        try {
            IndexResponse indexResponse = restHighLevelClient.index(request, RequestOptions.DEFAULT);
            log.info(indexResponse.toString());
            log.info("热搜保存es回调...: " + indexResponse.toString());
        } catch (IOException e) {
            e.printStackTrace();
            log.error(e.toString());
            throw new Uit3jcloudException("保存es信息异常", e);
        }
    }


}
